package authentication.interceptors;

import authentication.IMembershipProvider;
import authentication.annotations.Auth;
import authentication.annotations.LoginAction;
import authentication.components.LoginHandler;
import br.com.caelum.vraptor.InterceptionException;
import br.com.caelum.vraptor.Intercepts;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.core.InterceptorStack;
import br.com.caelum.vraptor.interceptor.Interceptor;
import br.com.caelum.vraptor.resource.ResourceMethod;

@Intercepts
public class AuthenticationInterceptor implements Interceptor {

    private final IMembershipProvider membershipProvider;
    private final LoginHandler loginHandler;
    private final Result result;

    public AuthenticationInterceptor(IMembershipProvider membershipProvider, LoginHandler loginHandler, Result result) {
        this.membershipProvider = membershipProvider;
        this.loginHandler = loginHandler;
        this.result = result;
    }

    @Override
    public boolean accepts(ResourceMethod method) {
        return method.containsAnnotation(Auth.class) && !method.containsAnnotation(LoginAction.class);
    }

    @Override
    public void intercept(InterceptorStack stack, ResourceMethod method, Object object) throws InterceptionException {
        if (!membershipProvider.isAuthenticated()) {
            loginHandler.redirectToLogin(result);
        } else {
            stack.next(method, object);
        }
    }
}
